package com.example.fourtestapp.ui;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.example.fourtestapp.R;
import com.example.fourtestapp.entity.LightInfo;
import com.example.fourtestapp.entity.MessgInfo;
import com.example.fourtestapp.utils.HttpUtils;
import com.example.fourtestapp.utils.ParamUtlis;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class TrafficLightFragment extends Fragment {
    private View view;
    private Spinner sp;
    private Button chaxun;
    private ListView lisview;
    private Button piliangxiugai;
    private myAdpter myAdpter;
    private MessgInfo messgInfo = new MessgInfo();

    private List<String> paixus = new ArrayList<>();
    private LightInfo lightInfo = new LightInfo();
    private List<String> duoxuan = new ArrayList<>();


     Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    if (myAdpter == null) {
                        myAdpter = new myAdpter();
                        lisview.setAdapter(myAdpter);
                    }
                    myAdpter.notifyDataSetChanged();
                    break;
                case 404:
                    Toast.makeText(getContext(), "批量修改失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 600:
                    Toast.makeText(getContext(), "修改成功！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_light, container, false);
        paixus.clear();
        initView(view);
        GetData();
        initListeren();
        return view;
    }

    private void GetData() {
        String data = new ParamUtlis().setParam("UserName", "user1").setParam("OrderBy", "1").build();
        HttpUtils.Post("/GetAllTrafficLights", data, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String data = response.body().string();
                lightInfo = new Gson().fromJson(data, LightInfo.class);
                handler.sendEmptyMessage(200);
            }
        });
    }

    private void initListeren() {
        chaxun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(), "功能未开放", Toast.LENGTH_SHORT).show();
            }
        });

        piliangxiugai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //对话框
                final View dv = LayoutInflater.from(getContext()).inflate(R.layout.dig_light, null);
                final AlertDialog dialog = new AlertDialog
                        .Builder(getContext())
                        .setTitle("红绿灯参数设置")
                        .setView(dv)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                final EditText redtime = dv.findViewById(R.id.redtime);
                                EditText yellowtime = dv.findViewById(R.id.yellowtime);
                                EditText greentime = dv.findViewById(R.id.greentime);
                                for (int j = 0; j < duoxuan.size(); j++) {
                                    String data = new ParamUtlis()
                                            .setParam("TrafficLightId", duoxuan.get(0) + "")
                                            .setParam("RedTime", redtime.getText().toString())
                                            .setParam("GreenTime", greentime.getText().toString())
                                            .setParam("YellowTime", yellowtime.getText().toString())
                                            .setParam("UserName", "user1")
                                            .build();
                                    HttpUtils.Post("/SetTrafficLightConfig", data, new Callback() {
                                        @Override
                                        public void onFailure(Call call, IOException e) {
                                            e.printStackTrace();
                                        }

                                        @Override
                                        public void onResponse(Call call, Response response) throws IOException {
                                            String datar = response.body().string();
                                            messgInfo = new Gson().fromJson(datar, MessgInfo.class);
                                            if (!messgInfo.getERRMSG().equals("成功")) {
                                                handler.sendEmptyMessage(404);
                                            } else {
                                                handler.sendEmptyMessage(600);
                                            }
                                        }
                                    });

                                }
                            }
                        })
                        .setNegativeButton("取消", null).create();
                dialog.show();
            }
        });
    }


    private void initView(View view) {
        piliangxiugai = view.findViewById(R.id.piliangxiugai);
        sp = view.findViewById(R.id.sp);
        chaxun = view.findViewById(R.id.chaxun);
        lisview = view.findViewById(R.id.lisview);
        paixus.add("一");
        paixus.add("二");
        ArrayAdapter arrayAdapter = new ArrayAdapter(getContext(), android.R.layout.simple_list_item_1, paixus);
        sp.setAdapter(arrayAdapter);
    }


    class myAdpter extends BaseAdapter {

        private MessgInfo messgInfo = new MessgInfo();
        private CheckBox checkbox;
        private TextView lukou;
        private TextView red;
        private TextView yellwo;
        private TextView green;
        private Button btn;

        @Override
        public int getCount() {
            return lightInfo.getROWS_DETAIL().size();
        }

        @Override
        public Object getItem(int i) {
            return lightInfo.getROWS_DETAIL().get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            view = LayoutInflater.from(getContext()).inflate(R.layout.light_list_item, viewGroup, false);
            initView(view);
            lukou.setText(lightInfo.getROWS_DETAIL().get(i).getIntersectionId() + "");
            red.setText(lightInfo.getROWS_DETAIL().get(i).getRedTime() + "");
            yellwo.setText(lightInfo.getROWS_DETAIL().get(i).getYellowTime() + "");
            green.setText(lightInfo.getROWS_DETAIL().get(i).getGreenTime() + "");

            checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        duoxuan.add(lightInfo.getROWS_DETAIL().get(i).getIntersectionId() + "");
                    } else {
                        duoxuan.remove(lightInfo.getROWS_DETAIL().get(i).getIntersectionId() + "");
                    }
                }
            });
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View view) {
                    //对话框
                    final View dv = LayoutInflater.from(getContext()).inflate(R.layout.dig_light, null);
                    final AlertDialog dialog = new AlertDialog
                            .Builder(getContext())
                            .setTitle("红绿灯参数设置")
                            .setView(dv)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    final EditText redtime = dv.findViewById(R.id.redtime);
                                    EditText yellowtime = dv.findViewById(R.id.yellowtime);
                                    EditText greentime = dv.findViewById(R.id.greentime);
                                    String data = new ParamUtlis()
                                            .setParam("TrafficLightId", lightInfo.getROWS_DETAIL().get(i + 1).getTrafficLightId() + "")
                                            .setParam("RedTime", redtime.getText().toString())
                                            .setParam("GreenTime", greentime.getText().toString())
                                            .setParam("YellowTime", yellowtime.getText().toString())
                                            .setParam("UserName", "user1")
                                            .build();
                                    HttpUtils.Post("/SetTrafficLightConfig", data, new Callback() {
                                        @Override
                                        public void onFailure(Call call, IOException e) {
                                            e.printStackTrace();
                                        }

                                        @Override
                                        public void onResponse(Call call, Response response) throws IOException {
                                            String data = response.body().string();
                                            messgInfo = new Gson().fromJson(data, MessgInfo.class);
                                            if (messgInfo.getERRMSG().equals("成功")) {
                                                Message message = new Message();
                                                message.what = 600;
                                                message.obj = messgInfo.getERRMSG();
                                                handler.sendMessage(message);
                                            } else {
                                                Toast.makeText(getContext(), "修改失败", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                }

                            })
                            .setNegativeButton("取消", null).create();
                    dialog.show();
                }
            });
            return view;
        }

        private void initView(View view) {
            checkbox = view.findViewById(R.id.checkbox);
            lukou = view.findViewById(R.id.lukou);
            red = view.findViewById(R.id.red);
            yellwo = view.findViewById(R.id.yellwo);
            green = view.findViewById(R.id.green);
            btn = view.findViewById(R.id.btn);
        }
    }
}
